﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using Utilities;

namespace QuartzNetService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            MainJob.JobStart();
        }

        protected override void OnStop()
        {
            MainJob.JobEnd();
        }
    }
    /// <summary>
    /// 任务调用类
    /// </summary>
    public static class MainJob
    {
        private static string configpath = "pamer.config";
        /// <summary>
        /// 定时任务方法入口
        /// </summary>
        public static void JobStart()
        {
            ISchedulerFactory sf = new StdSchedulerFactory();//内存调度
            IScheduler scheduler = sf.GetScheduler();
            /*
             * job1：job的名字
             * mygroup：分组（同一分组里面的job名称必须唯一）
             * UsingJobData：参数数组
             * */
            IJobDetail job = JobBuilder.Create<Quartzjob>().WithIdentity("job1", "mygroup").UsingJobData("key","value").UsingJobData("key1","value1").Build();
           
            ITrigger trigger = TriggerBuilder.Create().StartAt(DateTime.Now.AddSeconds(5)).WithCronSchedule(XMLProcess.Read(configpath, "Time")).Build();
            scheduler.ScheduleJob(job, trigger);
            scheduler.Start();
        }
        public static void JobEnd()
        {
            var FilePath = $@"{ConfigurationManager.AppSettings["Log"]}{DateTime.Now:yyyy-MM-dd}.txt";
            try
            {
                using (
                    var filestream = new System.IO.FileStream(FilePath, System.IO.FileMode.Append,
                        System.IO.FileAccess.Write, FileShare.ReadWrite))
                {
                    using (var sw = new StreamWriter(filestream, Encoding.GetEncoding("gb2312")))
                    {
                        sw.WriteLine("---------------------------------------------------------");
                        sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]");
                        sw.WriteLine("定时任务结束执行");
                        sw.WriteLine($"{XMLProcess.Read(configpath, "Name")}");
                        sw.WriteLine("---------------------------------------------------------");
                        sw.Flush();
                    }
                   
                }
            }
            catch (Exception e)
            {
               
                throw;
            }

        }
    }
}
